package com.atguigu.gmall.realtime.common.function;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.common.bean.DimJoinFunction;
import com.atguigu.gmall.realtime.common.constant.Constant;
import com.atguigu.gmall.realtime.common.util.HBaseUtil;
import com.atguigu.gmall.realtime.common.util.RedisUtil;
import io.lettuce.core.api.StatefulRedisConnection;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.async.ResultFuture;
import org.apache.flink.streaming.api.functions.async.RichAsyncFunction;
import org.apache.hadoop.hbase.client.AsyncConnection;

import java.util.Collections;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * @author Felix
 * @date 2024/8/05
 * 发送异步请求进行维度关联的模板类
 */
public abstract class DimAsyncFunction<T> extends RichAsyncFunction<T, T> implements DimJoinFunction<T> {

    private StatefulRedisConnection<String, String> asyncRedisConn;
    private AsyncConnection asyncHBaseConn;

    @Override
    public void open(Configuration parameters) throws Exception {
        asyncRedisConn = RedisUtil.getRedisAsyncConnection();
        asyncHBaseConn = HBaseUtil.getHBaseAsyncConnection();
    }

    @Override
    public void close() throws Exception {
        RedisUtil.closeRedisAsyncConnection(asyncRedisConn);
        HBaseUtil.closeHBaseAsyncConnection(asyncHBaseConn);
    }

    @Override
    public void asyncInvoke(T obj, ResultFuture<T> resultFuture) throws Exception {
        //创建异步编排对象   执行线程任务，有返回值
        CompletableFuture.supplyAsync(
                new Supplier<JSONObject>() {
                    @Override
                    public JSONObject get() {
                        //先从Redis中获取要关联的维度---异步
                        JSONObject dimJsonObj = RedisUtil.readDimAsync(asyncRedisConn, getTableName(), getRowKey(obj));
                        return dimJsonObj;
                    }
                }
                //执行线程任务  有入参，有返回值    上一个线程任务的返回结果会作为当前线程任务的入参
        ).thenApplyAsync(
                new Function<JSONObject, JSONObject>() {
                    @Override
                    public JSONObject apply(JSONObject dimJsonObj) {
                        if (dimJsonObj != null) {
                            //如果从Redis中获取到了要关联的维度，直接将其作为返回值返回(缓存命中)
                            System.out.println("~~~从Redis中获取维度表" + getTableName() + "的" + getRowKey(obj) + "数据~~~");
                        }else{
                            //如果从Redis中没有获取到要关联的维度，发送请求到HBase中查询维度---异步
                            dimJsonObj = HBaseUtil.readDimAsync(asyncHBaseConn, Constant.HBASE_NAMESPACE, getTableName(), getRowKey(obj));
                            if(dimJsonObj != null){
                                System.out.println("~~~从HBase中获取维度表" + getTableName() + "的" + getRowKey(obj) + "数据~~~");
                                //将从HBase中查询的结果放到Redis中缓存起来---异步
                                RedisUtil.writeDimAsync(asyncRedisConn,getTableName(), getRowKey(obj),dimJsonObj);
                            }else{
                                System.out.println("~~~没有找到维度表" + getTableName() + "的" + getRowKey(obj) + "数据~~~");
                            }
                        }
                        return dimJsonObj;
                    }
                }
                //创建线程任务   有入参，无返回值
        ).thenAcceptAsync(
                new Consumer<JSONObject>() {
                    @Override
                    public void accept(JSONObject dimJsonObj) {
                        //将维度属性补充到流中对象上
                        addDims(obj,dimJsonObj);
                        //获取数据库交互的结果并发送给ResultFuture的回调函数
                        resultFuture.complete(Collections.singleton(obj));
                    }
                }
        );
    }

    @Override
    public void timeout(T input, ResultFuture<T> resultFuture) throws Exception {
        throw new RuntimeException("如果关联发生了异常，请做如下检查:\n" +
                "相关进程是否启动:zk、kafka、maxwell、redis、hdfs、hbase\n" +
                "确认是否进行了维度历史数据的初始化\n" +
                "找昌平彦祖\n");
    }
}
